package com.software.graduationproject.commons.handler;

import com.software.graduationproject.commons.exception.ServiceException;
import com.software.graduationproject.commons.util.Result;
import com.software.graduationproject.commons.util.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自定义异常返回值格式
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    // 处理特定异常，比如自定义的业务异常
    @ExceptionHandler(ServiceException.class)
    public ResponseEntity<Object> handleCustomBusinessException(ServiceException ex, WebRequest request) {
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("message", ex.getMessage());
        responseBody.put("errorCode", ex.getCode());
        responseBody.put("timestamp", System.currentTimeMillis());
        responseBody.put("path", request.getContextPath());

        return new ResponseEntity<>(responseBody, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<Object> methodArgumentNotValidException(MethodArgumentNotValidException e){
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> collect = allErrors.stream()
                .map(error -> error.getDefaultMessage())
                .collect(Collectors.toList());
        Result<Object> failure = Results.failure(collect.toString());
        log.error(collect.toString());
        return new ResponseEntity<>(failure, HttpStatus.BAD_REQUEST);
    }
//    private void logValidationErrors(List<String> errorMessages) {
//        throw new ValidationException(errorMessages.toString());
//    }
//
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
//    private static class ValidationException extends RuntimeException {
//        public ValidationException(String message) {
//            super(message);
//        }
//    }
}
